#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2013-9-6

@author: iori
'''

# system libs
import os
import hashlib, zlib

# third part libs
import requests

# user libs
import const

def get_session():
    '''返回一个常规会话对象 '''
    sn = requests.Session()
    sn.headers = const.COMMON_HEADERS.copy()
    return sn

class RangeFile(object):
    def __init__(self, fname, start=0 , length=0):
        ''' 文件对象，但只取部分内容
             seek_end后再用 ftell返回值 为file_sizeһ�
        '''
        self.fp = open(fname, 'rb')
        self.start = start
        if length==0: length = os.path.getsize(fname)
        self.length = length
        self.end = self.start + self.length
        self.fp.seek(0, os.SEEK_END)
        self.fp.seek(start)
    def read(self, n=0):
        pos = self.fp.tell()
        if pos >= self.end:
            return None
        if n<=0:
            return self.fp.read(self.end - pos)
        else:
            n = min(n, self.end-pos)
            return self.fp.read(n)
    def dump(self):
        print self.read()

def md5_file(path):
    md5 = hashlib.md5()
    with open(path, 'rb') as fp:
        # 128*md5.block_size can improve performance
        for chunk in iter(lambda : fp.read(128*md5.block_size), ''):
            md5.update(chunk)
    return md5.hexdigest()

def md5_str(s):
    md5 = hashlib.md5()
    md5.update(s)
    return md5.hexdigest()

def crc32_file(path):
    prev = 0
    for line in open(path, 'rb') :
        prev = zlib.crc32(line, prev)
    return "%X"%(prev&0xFFFFFFFF)

def pcs_path_safe(path):
    ''' 路径长度限制为1000
                    路径中不能包含以下字符：\\ ? | " > < : *
                    文件名或路径名开头结尾不能是“.”或空白字符，空白字符包括: \r, \n, \t, 空格, \0, \x0B
    '''
    prefix, name = os.path.split(path)
    if prefix:
        prefix = prefix.translate(None, '\\?|"><')
    if not prefix:
        prefix = ''
    if name.startswith('.'):
        name = name[1:]
    name = name.strip()
    return prefix + '/' + name

